<template>
  <div class="search-container" style="position: relative;">
    <a-input-group compact>
      <a-input
        :value="displayValue"
        placeholder="请输入用户姓名搜索"
        :loading="loading"
        @input="handleInputImmediate"
        @blur="handleBlur"
        allow-clear
        @clear="handleClear"
        style="width: calc(100% - 32px)"
      />
      <a-button @click="openSelector">
        <template #icon><SearchOutlined /></template>
      </a-button>
    </a-input-group>

    <!-- 搜索结果下拉列表 -->
    <div 
      v-if="showDropdown && searchResults.length > 0" 
      class="search-dropdown"
    >
      <div
        v-for="user in searchResults"
        :key="user.id"
        class="search-item"
        @click="selectUser(user)"
      >
        <div class="user-info">
          <span class="user-name">{{ user.realName || user.userName }}</span>
          <span class="user-dept" v-if="user.deptName">{{ user.deptName }}</span>
        </div>
      </div>
    </div>

    <!-- 用户选择器 -->
    <UserSelect
      :visible="selectorVisible"
      :multiple="false"
      @update:visible="selectorVisible = $event"
      @ok="handleSelectFromModal"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue';
import { SearchOutlined } from '@ant-design/icons-vue';
import { debounce } from 'lodash-es';
import UserSelect from './UserSelect.vue';
import Api from '@/api/';

interface User {
  id: string;
  userName: string;
  realName?: string;
  deptName?: string;
  [key: string]: any;
}

const props = defineProps<{
  value?: string;
  placeholder?: string;
  disabled?: boolean;
}>();

const emit = defineEmits<{
  'update:value': [value: string | undefined];
  'change': [value: string | undefined, user?: User];
  'select': [user: User];
}>();

// 响应式数据
const searchResults = ref<User[]>([]);
const selectedUser = ref<User | null>(null);
const displayValue = ref('');
const selectorVisible = ref(false);
const loading = ref(false);
const showDropdown = ref(false);

// 输入处理 - 带防抖
const handleInput = debounce(async (e: any) => {
  const searchValue = e.target.value;
  
  if (!searchValue || searchValue.trim().length < 2) {
    searchResults.value = [];
    showDropdown.value = false;
    return;
  }

  loading.value = true;
  showDropdown.value = true;
  
  try {
    const result = await Api.user.users({
      index: 1,
      pageSize: 20,
      key: searchValue.trim()
    });
    
    searchResults.value = result.items || [];
    
    // 确保有结果时显示下拉框
    if (searchResults.value.length > 0) {
      showDropdown.value = true;
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    searchResults.value = [];
  } finally {
    loading.value = false;
  }
}, 100);

// 直接输入处理（不防抖，用于实时更新displayValue）
const handleInputImmediate = (e: any) => {
  const value = e.target.value;
  displayValue.value = value;
  
  // 处理完全清空的情况
  if (!value || value === '') {
    selectedUser.value = null;
    searchResults.value = [];
    showDropdown.value = false;
    emit('update:value', '');
    emit('change', '', null);
    return;
  }
  
  // 立即处理短输入的情况
  if (value.trim().length < 2) {
    searchResults.value = [];
    showDropdown.value = false;
    return;
  }
  
  // 对于长输入，调用防抖搜索
  handleInput(e);
};

// 选择用户
const selectUser = (user: User) => {
  selectedUser.value = user;
  displayValue.value = user.realName || user.userName;
  showDropdown.value = false;
  emit('update:value', user.id);
  emit('change', user.id, user);
  emit('select', user);
};

// 清空选择
const handleClear = () => {
  selectedUser.value = null;
  displayValue.value = '';
  searchResults.value = [];
  showDropdown.value = false;
  emit('update:value', '');
  emit('change', '', null);
};

// 失焦处理
const handleBlur = () => {
  setTimeout(() => {
    showDropdown.value = false;
  }, 200);
};

// 打开用户选择器
const openSelector = () => {
  selectorVisible.value = true;
};

// 从模态框选择用户
const handleSelectFromModal = async (userId: string) => {
  if (userId) {
    try {
      // 根据用户ID获取用户信息
      const user = await Api.user.get(userId);
      if (user) {
        selectedUser.value = user;
        displayValue.value = user.realName || user.userName;
        emit('update:value', user.id);
        emit('change', user.id, user);
        emit('select', user);
      }
    } catch (error) {
      console.error('获取用户信息失败:', error);
      // 如果获取失败，尝试使用基本信息
      selectedUser.value = { id: userId, userName: userId, realName: userId };
      displayValue.value = userId;
      emit('update:value', userId);
      emit('change', userId, selectedUser.value);
      emit('select', selectedUser.value);
    }
  }
  selectorVisible.value = false;
};

// 根据用户ID获取用户信息并显示名称
const loadUserInfo = async (userId: string) => {
  if (!userId || userId === '' || userId === null || userId === undefined) {
    selectedUser.value = null;
    displayValue.value = '';
    return;
  }

  try {
    const user = await Api.user.get(userId);
    if (user) {
      selectedUser.value = user;
      displayValue.value = user.realName || user.userName;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    selectedUser.value = null;
    displayValue.value = '';
  }
};

// 监听value变化，自动加载用户信息
watch(() => props.value, async (newValue) => {
  if (newValue && newValue.trim && newValue.trim() !== '' && (!selectedUser.value || selectedUser.value.id !== newValue)) {
    await loadUserInfo(newValue);
  } else if (!newValue || newValue === '' || newValue === null || newValue === undefined) {
    displayValue.value = '';
    selectedUser.value = null;
    searchResults.value = [];
    showDropdown.value = false;
  }
}, { immediate: true });

// 组件挂载时初始化
onMounted(() => {
  if (props.value) {
    loadUserInfo(props.value);
  }
});
</script>

<style scoped>
.search-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 9999;
  background: white;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 200px;
  overflow-y: auto;
  margin-top: 2px;
}

.search-item {
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.search-item:hover {
  background-color: #f5f5f5;
}

.search-item:last-child {
  border-bottom: none;
}

.user-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-name {
  font-weight: 500;
  color: #333;
}

.user-dept {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}

/* 确保容器有相对定位 */
.search-container {
  position: relative !important;
}

.ant-input-group {
  position: relative;
}
</style> 